"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 备机事务隔离性read committed测试
Create At   : 2023/07/19
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建测试表
    3.备机开启事务，查询表
    4.主机开启事务，表中插入数据，提交
    5.备机再次查询，提交
    6.清理环境
Expect      :
    1.修改成功
    2.执行成功
    3.无数据
    4.成功
    5.成功，1条数据
    6.成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table = 't_multi_node_write_0070'
        self.enable_remote_execute = 'enable_remote_execute'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.log.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')

        step2 = "-----step2:创建测试表;expect:成功-----"
        self.log.info(step2)
        sql_msg = self.standby_sh.execut_db_sql(
            f'''drop table if exists {self.table} cascade;
            create table {self.table}(
            prod_id       NUMBER(6),
            cust_id       NUMBER,
            time_id       DATE ) with(segment=on) 
            PARTITION BY RANGE (time_id) INTERVAL('1 day')( 
            PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'),
            PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00'));''')
        self.log.info(sql_msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(5)

        step3 = "-----step3:备机开启事务，查询表;expect:无数据;" \
                "step5:备机再次查询，提交;expect:成功-----"
        self.log.info(step3)
        sql = f'''begin isolation level read committed;
        select * from {self.table};
        select pg_sleep(5);
        select * from {self.table};
        commit;'''
        self.log.info(sql)
        session1 = ComThread(self.standby_sh.execut_db_sql, args=(sql,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(2)

        step4 = "-----step4:主机开启事务，表中插入数据，提交;expect:成功-----"
        self.log.info(step4)
        sql2 = f'''begin;
        insert into {self.table} values(1, 2, date'2023-06-21');
        commit;'''
        session2 = ComThread(PrimarySh.execut_db_sql, args=(sql2,))
        session2.setDaemon(True)
        session2.start()
        session1.join(30)
        session2.join(60)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn('BEGIN', res1, f"执行失败: {step3}")
        self.assertIn('(0 rows)', res1.splitlines()[3], f"执行失败: {step3}")
        self.assertIn('1 |       2 | 2023-06-21 00:00:00', res1,
                      f"执行失败: {step3}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res1, f"执行失败: {step3}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res2, f"执行失败:{step4}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res2, f"执行失败: {step4}")

    def tearDown(self):
        step6 = "-----step6:恢复参数;expect:恢复参数成功-----"
        self.log.info(step6)
        drop_res = self.standby_sh.execut_db_sql(
            f'drop table if exists {self.table} cascade;')
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_res,
                      f'执行失败:{step6}')
        self.assertTrue(result1, f'执行失败:{step6}')
        self.assertTrue(restart_res, f'执行失败:{step6}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step6}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
